package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.SpeedLoanProductRcAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.SpeedOrProduct;
import com.cardbaobao.cardbabyclient.model.result.BannerResult;
import com.cardbaobao.cardbabyclient.model.result.SpeedOrProductResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.LocationUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.RecyclerViewWithFooter.OnLoadMoreListener;
import com.cardbaobao.cardbabyclient.widget.RecyclerViewWithFooter.RecyclerViewWithFooter;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.xbanner.XBanner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Description: 極速貸款
 * Created by FHW
 * on 2017/6/16
 */
public class SpeedLoanActivity extends BaseActivity implements View.OnClickListener {
    public static int RESULT_CODE = 1;
    public static final String CODE = "code";
    public static final String TITLE_S = "title";
    public static final String GO_HOME_B="goHome";//是否直接回到首页
    @BindView(R.id.tw_toolbar)
    TitleBar tw_toolbar;

    @BindView(R.id.main_appbar)
    AppBarLayout main_appbar;
    @BindView(R.id.xb_banner)
    XBanner xb_banner;
    @BindView(R.id.rv_speed_loan)
    RecyclerViewWithFooter rv_speed_loan;
    @BindView(R.id.srLayout)
    SmartRefreshLayout srLayout;

    @BindView(R.id.ll_hot)
    LinearLayout ll_hot;
    @BindView(R.id.ll_quota)
    LinearLayout ll_quota;
    @BindView(R.id.ll_loan_fast)
    LinearLayout ll_loan_fast;
    @BindView(R.id.ll_rates_low)
    LinearLayout ll_rates_low;

    @BindView(R.id.tv_hot)
    TextView tv_hot;
    @BindView(R.id.tv_quota)
    TextView tv_quota;
    @BindView(R.id.tv_loan_fast)
    TextView tv_loan_fast;
    @BindView(R.id.tv_rates_low)
    TextView tv_rates_low;
    @BindView(R.id.iv_hot)
    ImageView iv_hot;
    @BindView(R.id.iv_quota)
    ImageView iv_quota;
    @BindView(R.id.iv_loan_fast)
    ImageView iv_loan_fast;
    @BindView(R.id.iv_rates_low)
    ImageView iv_rates_low;

    private SpeedLoanProductRcAdapter mAdapter;
    private List<SpeedOrProduct.LoanListBean> loan_list;

    private int mType = 0;//0-热门 1-额度高 2-放款快 3-利率低
    private boolean isLoading = false;
    private ArrayList<Banner.CarouselFigureListBean> bannerList;

    private int mPage = 1;
    private String mOrder = Constant.LOAN_HOT;//默认值：loan_hot（热门）
    private String code = "ECP02010501";//资质分类代码

    private String title = "";

    @BindView(R.id.ll_no_data)
    LinearLayout ll_no_data;

    private boolean goHome;
    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName(Google.SPEED_LOANS);
        UmengEventUtils.pageEvent(mContext,getString(R.string.event_0x04a));
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        bannerList = new ArrayList<>();
        loan_list = new ArrayList<>();

        mCurrentPageId= Self.Page.app_fast_loan_page;

        Intent intent=getIntent();
        code = intent.getStringExtra(CODE);
        title = intent.getStringExtra(TITLE_S);
        goHome=intent.getBooleanExtra(GO_HOME_B,false);

        if (title != null)
            tw_toolbar.setTitleText(title);

        ll_hot.setOnClickListener(this);
        ll_quota.setOnClickListener(this);
        ll_loan_fast.setOnClickListener(this);
        ll_rates_low.setOnClickListener(this);

        getBannerPic();

        srLayout.setEnableLoadmore(false);
        final LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        rv_speed_loan.setLayoutManager(layoutManager);
        setRvData();
        getSpeedLoanData(true);

        tw_toolbar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleBack();
            }
        });

        rv_speed_loan.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getSpeedLoanData(false);
            }
        });
        srLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                onRefreshRv();
            }
        });
        rv_speed_loan.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&
                        layoutManager.findFirstCompletelyVisibleItemPosition()==0){
                    main_appbar.setExpanded(true,true);
                }
            }
        });
    }

    private void onRefreshRv() {
        mPage = 1;
        rv_speed_loan.setEmpty();
        getSpeedLoanData(true);
    }

    private void getSpeedLoanData(final boolean isClean) {
        Map<String,Object> params = new HashMap<>();
        params.put("index", String.valueOf(mPage));
        params.put("size", String.valueOf(Constant.SIZE));
        params.put("order", mOrder);
        params.put("code", code);
        if (!TextUtils.isEmpty(LocationUtil.getCityName())) {
            params.put("city", LocationUtil.getCityName());
        }
        if (isClean){
            showProgressDialog(true);
        }
        Observable<String> observable= Api.speedLoanData(params);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
                srLayout.finishRefresh();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                SpeedOrProductResult speedOrProductResult = JsonUtil.json2Object(s, SpeedOrProductResult.class);
                if (speedOrProductResult.getCode() == Constant.SUC_CODE) {
                    if (speedOrProductResult.getData() != null) {

                        if (speedOrProductResult.getData().getLoan_list() != null && speedOrProductResult.getData().getLoan_list().size() > 0) {
                            srLayout.setVisibility(View.VISIBLE);
                            ll_no_data.setVisibility(View.GONE);
                        } else {
                            srLayout.setVisibility(View.GONE);
                            ll_no_data.setVisibility(View.VISIBLE);
                        }
                        if (isClean)
                            loan_list.clear();

                        loan_list.addAll(speedOrProductResult.getData().getLoan_list());
                        //分页
                        if (speedOrProductResult.getPage().getTotalPage() > mPage) {
                            mPage++;
                            rv_speed_loan.setLoading();
                        } else {
                            rv_speed_loan.setEnd("没有更多了");
                        }

                        mAdapter.setData(loan_list);
                    }
                } else {
                    ToastUtil.showToast(speedOrProductResult.getMsg());
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_speed_loan;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_hot:
                mType = 0;
                showTypeView();
                mOrder = Constant.LOAN_HOT;
                onRefreshRv();
                SelfUtils.buriedClickData(Self.Action.app_click_speed_loan_hottest,
                        Self.Action.app_click_speed_loan_hottest_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                break;
            case R.id.ll_quota:
                mType = 1;
                showTypeView();
                mOrder = Constant.LOAN_LIMIT;
                onRefreshRv();
                SelfUtils.buriedClickData(Self.Action.app_click_speed_loan_quota,
                        Self.Action.app_click_speed_loan_quota_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                break;
            case R.id.ll_loan_fast:
                mType = 2;
                showTypeView();
                mOrder = Constant.LOAN_SPEED;
                onRefreshRv();
                SelfUtils.buriedClickData(Self.Action.app_click_speed_loan_fast,
                        Self.Action.app_click_speed_loan_fast_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                break;
            case R.id.ll_rates_low:
                mType = 3;
                showTypeView();
                mOrder = Constant.LOAN_RATE;
                onRefreshRv();
                SelfUtils.buriedClickData(Self.Action.app_click_speed_loan_rate_lower,
                        Self.Action.app_click_speed_loan_rate_lower_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                break;
        }
    }

    private void showTypeView() {
        tv_hot.setTextColor(getResources().getColor(R.color.color_999999));
        tv_quota.setTextColor(getResources().getColor(R.color.color_999999));
        tv_loan_fast.setTextColor(getResources().getColor(R.color.color_999999));
        tv_rates_low.setTextColor(getResources().getColor(R.color.color_999999));
        iv_hot.setBackgroundResource(R.mipmap.icon_up_n);
        iv_quota.setBackgroundResource(R.mipmap.icon_up_n);
        iv_loan_fast.setBackgroundResource(R.mipmap.icon_up_n);
        iv_rates_low.setBackgroundResource(R.mipmap.icon_down_n);
        switch (mType) {
            case 0:
                tv_hot.setTextColor(getResources().getColor(R.color.color_FFAB18));
                iv_hot.setBackgroundResource(R.mipmap.icon_up_s);
                break;
            case 1:
                tv_quota.setTextColor(getResources().getColor(R.color.color_FFAB18));
                iv_quota.setBackgroundResource(R.mipmap.icon_up_s);
                break;
            case 2:
                tv_loan_fast.setTextColor(getResources().getColor(R.color.color_FFAB18));
                iv_loan_fast.setBackgroundResource(R.mipmap.icon_up_s);
                break;
            case 3:
                tv_rates_low.setTextColor(getResources().getColor(R.color.color_FFAB18));
                iv_rates_low.setBackgroundResource(R.mipmap.icon_down_s);
                break;
        }
    }


    private void setRvData() {
        mAdapter = new SpeedLoanProductRcAdapter(this);
        mAdapter.setBuriedInfo(mEnterPageTime,mCurrentPageId,mPrePageId);
        rv_speed_loan.setAdapter(mAdapter);
    }

    private void setBannerData() {
        //添加广告数据
        xb_banner.setData(bannerList, null);//第二个参数为提示文字资源集合
        xb_banner.setmAutoPalyTime(Constant.BANNER_INTERVAL_TIME);
        xb_banner.setmAdapter(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                ImageLoaderUtil.displayImage(URLUtil.CBB_IMG_URL + bannerList.get(position).getImage(), (ImageView) view);
            }
        });
        xb_banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, int position) {
                SelfUtils.buriedClickData(Self.Action.app_click_speed_loan_top_banner,
                        Self.Action.app_click_speed_loan_top_banner_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                CommonJumpController controller = new CommonJumpController(mContext);
                Banner.CarouselFigureListBean bean = bannerList.get(position);
                Map<String, Object> map = new HashMap<>();
                map.put(CommonJumpController.FROM_PAGE, getString(R.string.text_speed_loan));
                map.put(EventWebViewActivity.WEB_TYPE_I, 5);
                controller.bannerJump(bean, map);
            }
        });

    }

    /**
     * 获取轮播图
     */
    private void getBannerPic() {
        if (isLoading) {
            return;
        }
        isLoading = true;
        Observable<String> observable=Api.getBannerData(Constant.GLB0314);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                isLoading=false;
            }

            @Override
            public void onError(Throwable e) {
                isLoading=false;
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                BannerResult bannerResult = JsonUtil.json2Object(s, BannerResult.class);
                if (bannerResult.getCode() == Constant.SUC_CODE) {
                    if (bannerResult.getData() != null) {
                        bannerList.addAll(bannerResult.getData().getCarousel_figure_list());
                        if (bannerList.size() > 0) {
                            setBannerData();
                        } else {
                            xb_banner.setVisibility(View.GONE);
                        }
                    }
                } else {
                    ToastUtil.showToast(bannerResult.getMsg());
                }
            }
        });
    }

    @Override
    public void finish() {
        setResult(RESULT_CODE);
        super.finish();
    }

    private void handleBack(){
        if(goHome){
            Intent intent=new Intent(mContext,MainActivity.class);
            startActivity(intent);
            finish();
        }else{
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN){
            handleBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
